package com.itheima.service;


import com.alibaba.cloud.commons.lang.StringUtils;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.itheima.api.PeachblossomApi;
import com.itheima.exception.BusinessException;
import com.itheima.interceptor.UserHolder;
import com.itheima.server.ErrorResult;
import com.itheima.vo.Peachblossom;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class PeachblossomService {

    @DubboReference
    private PeachblossomApi peachblossomApi;

    @Autowired
    private FastFileStorageClient fastFileStorageClient;

    @Autowired
    private FdfsWebServer webServer;

    public void savePeachblossom(MultipartFile PeachblossomThumbnail) throws IOException {
        //判断是否有文件
        if (PeachblossomThumbnail.isEmpty()){
            throw new BusinessException(ErrorResult.error());
        }

        //获取原文件名
        String filename = PeachblossomThumbnail.getOriginalFilename();
        //根据.切割文件
        filename = filename.substring(filename.lastIndexOf(".") + 1);
        StorePath storePath = fastFileStorageClient.uploadFile(PeachblossomThumbnail.getInputStream(), PeachblossomThumbnail.getSize(), filename, null);
        String videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();

        //构建语音对象
        Peachblossom peachblossom=new Peachblossom();
        peachblossom.setUserId(UserHolder.getUserId());
        peachblossom.setVideoUrl(videoUrl);

        String peachblossomId = peachblossomApi.save(peachblossom);
        if(StringUtils.isEmpty(peachblossomId)) {
            throw new BusinessException(ErrorResult.error());
        }


    }
}
